package com.janke.softballnexus.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.janke.softballnexus.client.ui.LoginPanel;
import com.janke.softballnexus.client.ui.MainPage;
import com.janke.softballnexus.shared.LoginInfo;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Softball implements EntryPoint, ValueChangeHandler<String> {

	private MainPage mainPanel = new MainPage();

	private LoginInfo loginInfo = null;
	private LoginPanel loginPanel = new LoginPanel();

	public void onModuleLoad() {
		final LoginServiceAsync loginService = GWT.create(LoginService.class);
		loginService.login(GWT.getHostPageBaseURL(),
				new AsyncCallback<LoginInfo>() {
					public void onFailure(Throwable error) {
					}

					public void onSuccess(LoginInfo result) {
						loginInfo = result;
						if (loginInfo.isLoggedIn()) {
							loadCMS();
						} else {
							loadLogin();
						}
					}
				});

		// geo = new Geocoder();
		//
		// geo.reset();
		// geo.setBaseCountryCode("CA");
		//
		// geo.getLatLng("362 Saginaw Parkway, Cambridge, ON",
		// new LatLngCallback() {
		//
		// @Override
		// public void onFailure() {
		// Window.alert("geocode failure");
		// }
		//
		// @Override
		// public void onSuccess(LatLng point) {
		// if (Window.confirm(point == null ? "null point"
		// : "Lat " + point.getLatitude() + " Lng "
		// + point.getLongitude())) {
		// }
		//
		// }
		// });

		// String initToken = History.getToken();
		// if (initToken.length() == 0) {
		// History.newItem("home");
		// }
		//
		// RootLayoutPanel.get().add(mainPanel);
		//
		// History.addValueChangeHandler(this);
		//
		// History.fireCurrentHistoryState();
		//
		// Mediator.getInstance().initialize();
	}

	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
		// if (event.getValue().equals("home")) {
		// mainPanel.setContent(new Label("home"));
		// } else if (event.getValue().equals("schedules")) {
		// mainPanel.setContent(new Label("schedules"));
		// // } else if (event.getValue().equals("contact")) {
		// // mainPanel.setContent(contact);
		// }
	}

	private void loadLogin() {
		// Assemble login panel.
		loginPanel.setAnchorUrl(loginInfo.getLoginUrl());
		RootLayoutPanel.get().add(loginPanel);
	}

	private void loadCMS() {
		// Assemble login panel.
		RootLayoutPanel.get().add(
				new Anchor("Sign Out", loginInfo.getLogoutUrl()));
	}
}
